<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div class="localvideo">
        <video src=""></video>
    </div>
    <div>
        <button onclick="start()">开始录制</button>
        <button onclick="stop()">停止</button>
    </div>
    <script>
        let recorder
        navigator.mediaDevices.getUserMedia({ video: true })
        .then(stream => {
            const video = document.querySelector('video');
            video.srcObject = stream;
            video.play();

            let options = { mimeType: 'video/webm; codecs=vp9' };
            recorder = new MediaRecorder(stream, options);

            let blobs = []
            // 将开始录制的视频保存到blobs中
            recorder.ondataavailable = event => {
                blobs.push(event.data);
            };

            recorder.onstop = function() {
                // 创建可下载的链接
                console.log(blobs);
                blobs.forEach((blob,i)=>{
                    const url = URL.createObjectURL(blob);
                    const downloadLink = document.createElement('a');
                    downloadLink.href = url;
                    downloadLink.download = 'test'+i+'.webm'; // 设置文件名
                    downloadLink.click(); // 触发点击事件，开始下载
                    URL.revokeObjectURL(url);
                })
                // 释放对象URL资源
                setTimeout(() => {
                    blobs = []
                }, 100);
            };

        })
        .catch(err => console.error(err));

        function start(){
            recorder.start()
        }

        function stop(){
            recorder.stop()
        }
    </script>
</body>
</html>